package order;

import enums.GoodsType;
import models.BaseModel;
import models.constants.DeletedStatus;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.Map;

/**
 * 订单来源
 * Created by youliangcheng on 17/6/12.
 */
@Entity
@Table(name = "order_sources")
public class OrderSource extends BaseModel {

    /**
     * 来源名称
     */
    @Column(name = "name")
    public String name ;

    /**
     * 来源编号
     */
    @Column(name = "code")
    public String code ;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark ;

    public static JPAExtPaginator<OrderSource> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.name like {name} ~/")
                .append("/~ and t.code like {code} ~/");



        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        Logger.info("sql : %s" , result.getXsql());
        JPAExtPaginator<OrderSource> orderPage = new JPAExtPaginator<>("OrderSource t", "t", OrderSource.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }

    /**
     * 根据Id查询orderSource
     * @param id
     * @return
     */
    public static OrderSource findBySourceId(long id){
        return OrderSource.find("id = ? and deleted = ?" , id , DeletedStatus.UN_DELETED).first();
    }

    /**
     * 判断第三方平台数据是否被使用
     * @param id
     * @return
     */
    public static Boolean checkIsUsed(long id) {

        return Order.count(" goodsType = ? and orderSource.id = ? and deleted = ? ", GoodsType.THIRDPARTY, id, DeletedStatus.UN_DELETED) > 0;

    }

}
